var App = (function(App, $, _){

	'user strict';

	var river = {};
	var moduleName = "river"; // define a unique module name

	/* ==== PLACE MODULE CODE HERE ==== */

	/* onClick of a card, put your own photo next to the card. */

	/* When the host notifies everyone that the game has finished, get what people
	voted for and display them in the divs. */
	
	river.result = {"1":[],"3":[],"5":[],"13":[],"21":[],"55":[],"?":[]};
	
	/*App.on("gameFinished", function(gameStatus){
		_.each(gameStatus, function(participantId, participantStatus){
			if(participantStatus.cardSelected !== null){
				console.log(participantId);
				console.log(participantStatus);
				participantImageURL = gapi.hangout.getParticipantById(participantId).image.url;
				river.result[participantStatus.cardSelected].push(participantImageURL);
			}
		});

		$(".river").html("");

		_.each(river.result, function(cardValue, participantList){
			_.each(participantList, function(participantImageURL){
				imageTag = "<img src=\"" + participantImageURL + "\">";
				$("#" + cardValue + "-river").append(imageTag);
			});
		});
	});*/

	gapi.hangout.data.onStateChanged.add(function(){
		gameState = gapi.hangout.data.getValue("gameState");
		gameData = gapi.hangout.data.getValue("gameData");
		console.log("gameState " + gameState);
		console.log("gameData " + gameData);

		if(!gameState){
			return;
		} else if(gameState === "started"){
			river.result = {"1":[],"3":[],"5":[],"13":[],"21":[],"55":[],"?":[]};
		} else if(gameState === "finished"){
			gameData = JSON.parse(gameData);
			_.each(gameData, function(participantId, participantStatus){
				if(participantStatus.cardSelected !== null){
					console.log(participantId);
					console.log(participantStatus);
					participantImageURL = gapi.hangout.getParticipantById(participantId).image.url;
					river.result[participantStatus.cardSelected].push(participantImageURL);
				}
			});

			$(".river").html("");

			_.each(river.result, function(cardValue, participantList){
				_.each(participantList, function(participantImageURL){
					imageTag = "<img src=\"" + participantImageURL + "\">";
					$("#" + cardValue + "-river").append(imageTag);
				});
			});
		}
	});

	var ractive;

	river.update = function(dataTurns) {
		ractive.set("data.cards", dataTurns)
	}

	// default initialisation method (called when API and DOM are ready)
	river.init = function() {

		ractive = new Ractive({
		  el: $("#river"),
		  template: $("#river").html(),
		  data: {
		  	cards: []
		  }
		});

		App.on("dataTurns", river.update);

	};

	/* ================================ */

	// add module to list of modules
	App.modules = App.hasOwnProperty("modules") ? App.modules : {};
	App.modules[moduleName] = river;

	return App;

}(App || {}, $, _));